import json

import tornado

from db.model import Article
from db.user import User
from view.list_sub import buildPathTree, buildTimeTree, isIgnore


class TreePage(tornado.web.RequestHandler):
    def get(self):
        User.db.connect()
        allArticle = Article.select()
        folder_tree = {}
        for article in allArticle:
            if isIgnore(article.path):
                continue
            buildPathTree(folder_tree, article.title, article.path)

        timeArticle = allArticle.order_by(Article.date.desc())
        time_tree = {}
        for article in timeArticle:
            if isIgnore(article.path):
                continue
            buildTimeTree(time_tree, article.date, article.title, article.path)

        User.db.close()

        self.render('list-tree.html', folder_tree=json.dumps(folder_tree), time_tree=json.dumps(time_tree))


def get_tree_page():
    allArticle = Article.select()
    folder_tree = {}
    for article in allArticle:
        if isIgnore(article.path):
            continue
        buildPathTree(folder_tree, article.title, article.path)

    timeArticle = allArticle.order_by(Article.date.desc())
    time_tree = {}
    for article in timeArticle:
        if isIgnore(article.path):
            continue
        buildTimeTree(time_tree, article.date, article.title, article.path)
    return json.dumps(folder_tree), json.dumps(time_tree)
